package com.doujiang.Controller;

import com.doujiang.domain.User;
import com.doujiang.domain.AvatarUpdateRequest;
import com.doujiang.domain.dto.RegisterRequest;
import com.doujiang.domain.dto.SendCodeRequest;
import com.doujiang.domain.dto.ResetPasswordRequest;
import com.doujiang.service.IUserService;
import com.doujiang.service.VerificationCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/users")
@CrossOrigin
public class UserController {

    @Autowired
    private IUserService userService;
    
    @Autowired
    private VerificationCodeService verificationCodeService;

    // 查询所有用户
    @GetMapping
    public List<User> getAllUsers() {
        return userService.list();
    }
    //根据email查询用户
//    @GetMapping("/selectemail/{email}")
//    public User getUserByEmail(@PathVariable("email") String email) {
//        return userService.getUserByEmail(email);
//    }

    // 插入用户
    @PostMapping
    public String addUser(@RequestBody User user) {
        if (userService.save(user)) {
            return "用户插入成功";
        } else {
            return "用户插入失败";
        }
    }



    /**
     * 新增登录接口
     */
    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody User loginData) {
        User authenticatedUser = userService.authenticateAndGetUser(loginData.getEmail(), loginData.getPassword());
        if (authenticatedUser != null) {
            return ResponseEntity.ok(authenticatedUser); // 登录成功返回用户信息
        } else {
            return ResponseEntity.ok(false); // 登录失败返回false
        }
    }

    /**
     * 根据用户ID获取用户信息
     */
    @GetMapping("/{id}")
    public ResponseEntity<?> getUserById(@PathVariable("id") Long id) {
        User user = userService.getById(id);
        if (user != null) {
            // 不返回密码信息
            user.setPassword("******");
            return ResponseEntity.ok(user);
        } else {
            return ResponseEntity.status(404).body("用户不存在");
        }
    }

    /**
     * 根据邮箱获取用户信息
     */
    @GetMapping("/email/{email}")
    public ResponseEntity<?> getUserByEmail(@PathVariable String email) {
        User user = userService.getUserByEmail(email);
        if (user != null) {
            return ResponseEntity.ok(user);
        } else {
            return ResponseEntity.status(404).body("用户不存在");
        }
    }

    /**
     * 更新用户信息
     */
    @PutMapping("/{id}")
    public ResponseEntity<?> updateUser(@PathVariable("id") Long id, @RequestBody User userData) {
        User existingUser = userService.getById(id);
        if (existingUser != null) {
            userData.setId(id);
            
            // 如果新密码不为空且不是"******"，则更新密码
            if (userData.getPassword() != null && !userData.getPassword().equals("******") && !userData.getPassword().isEmpty()) {
                // 密码会被更新
            } else {
                // 保持原密码不变
                userData.setPassword(existingUser.getPassword());
            }
            
            if (userService.updateById(userData)) {
                // 返回更新后的用户信息（不包含密码）
                User updatedUser = userService.getById(id);
                updatedUser.setPassword("******"); // 不返回真实密码
                return ResponseEntity.ok(updatedUser);
            } else {
                return ResponseEntity.status(500).body("更新失败");
            }
        } else {
            return ResponseEntity.status(404).body("用户不存在");
        }
    }

    /**
     * 更新用户头像
     */
    @PutMapping("/{id}/avatar")
    public ResponseEntity<?> updateAvatar(@PathVariable("id") Long id, @RequestBody AvatarUpdateRequest request) {
        User existingUser = userService.getById(id);
        if (existingUser != null) {
            existingUser.setAvatar(request.getAvatarUrl());
            if (userService.updateById(existingUser)) {
                // 返回更新后的用户信息（不包含密码）
                User updatedUser = userService.getById(id);
                updatedUser.setPassword("******"); // 不返回真实密码
                return ResponseEntity.ok(updatedUser);
            } else {
                return ResponseEntity.status(500).body("头像更新失败");
            }
        } else {
            return ResponseEntity.status(404).body("用户不存在");
        }
    }

    /**
     * 发送验证码
     */
    @PostMapping("/send-code")
    public ResponseEntity<?> sendVerificationCode(@RequestBody SendCodeRequest request) {
        String email = request.getEmail();
        
        // 验证邮箱格式
        if (!isValidEmail(email)) {
            return ResponseEntity.badRequest().body("邮箱格式不正确");
        }
        
        // 检查邮箱是否已注册
        User existingUser = userService.getUserByEmail(email);
        if (existingUser != null) {
            return ResponseEntity.badRequest().body("该邮箱已注册");
        }
        
        // 发送验证码
        boolean success = verificationCodeService.generateAndSendCode(email);
        if (success) {
            return ResponseEntity.ok("验证码发送成功");
        } else {
            return ResponseEntity.badRequest().body("验证码发送失败，请稍后重试");
        }
    }

    /**
     * 用户注册（带验证码验证）
     */
    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody RegisterRequest request) {
        // 验证邮箱格式
        if (!isValidEmail(request.getEmail())) {
            return ResponseEntity.badRequest().body("邮箱格式不正确");
        }
        
        // 验证验证码
        if (!verificationCodeService.verifyCode(request.getEmail(), request.getCode())) {
            return ResponseEntity.badRequest().body("验证码错误或已过期");
        }
        
        // 检查邮箱是否已注册
        User existingUser = userService.getUserByEmail(request.getEmail());
        if (existingUser != null) {
            return ResponseEntity.badRequest().body("该邮箱已注册");
        }
        
        // 检查用户名是否已存在
        if (request.getUsername() != null && !request.getUsername().trim().isEmpty()) {
            // 这里可以添加用户名唯一性检查
        }
        
        // 创建新用户
        User newUser = new User();
        newUser.setEmail(request.getEmail());
        newUser.setPassword(request.getPassword());
        newUser.setUsername(request.getUsername());
        
        if (userService.save(newUser)) {
            // 注册成功，返回用户信息（不包含密码）
            User savedUser = userService.getUserByEmail(request.getEmail());
            savedUser.setPassword("******");
            return ResponseEntity.ok(savedUser);
        } else {
            return ResponseEntity.status(500).body("注册失败");
        }
    }

    /**
     * 验证邮箱格式
     */
    private boolean isValidEmail(String email) {
        String emailRegex = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$";
        return Pattern.matches(emailRegex, email);
    }

    /**
     * 发送重置密码验证码
     */
    @PostMapping("/send-reset-code")
    public ResponseEntity<?> sendResetCode(@RequestBody SendCodeRequest request) {
        String email = request.getEmail();
        
        // 验证邮箱格式
        if (!isValidEmail(email)) {
            return ResponseEntity.badRequest().body("邮箱格式不正确");
        }
        
        // 检查邮箱是否存在
        User existingUser = userService.getUserByEmail(email);
        if (existingUser == null) {
            return ResponseEntity.badRequest().body("该邮箱未注册");
        }
        
        // 发送重置密码验证码
        boolean success = verificationCodeService.generateAndSendCode(email, true);
        if (success) {
            return ResponseEntity.ok("验证码发送成功");
        } else {
            return ResponseEntity.badRequest().body("验证码发送失败，请稍后重试");
        }
    }

    /**
     * 重置密码
     */
    @PostMapping("/reset-password")
    public ResponseEntity<?> resetPassword(@RequestBody ResetPasswordRequest request) {
        // 验证邮箱格式
        if (!isValidEmail(request.getEmail())) {
            return ResponseEntity.badRequest().body("邮箱格式不正确");
        }
        
        // 验证验证码
        if (!verificationCodeService.verifyCode(request.getEmail(), request.getCode())) {
            return ResponseEntity.badRequest().body("验证码错误或已过期");
        }
        
        // 检查邮箱是否存在
        User existingUser = userService.getUserByEmail(request.getEmail());
        if (existingUser == null) {
            return ResponseEntity.badRequest().body("该邮箱未注册");
        }
        
        // 更新密码
        existingUser.setPassword(request.getNewPassword());
        if (userService.updateById(existingUser)) {
            return ResponseEntity.ok("密码重置成功");
        } else {
            return ResponseEntity.status(500).body("密码重置失败");
        }
    }
}





